import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'

export const TableToolbar = Extension.create({
  name: 'tableToolbar',

  onCreate() {
    const editor = this.editor;
    if (!editor) return;

    const toolbar = document.createElement('div');
    toolbar.className = 'fixed hidden gap-2 p-2 bg-white rounded-lg shadow-lg z-50';
    
    const buttons = [
      { text: '添加行', cmd: () => editor.chain().focus().addRowAfter().run() },
      { text: '添加列', cmd: () => editor.chain().focus().addColumnAfter().run() },
      { text: '删除行', cmd: () => editor.chain().focus().deleteRow().run(), class: 'text-red-600' },
      { text: '删除列', cmd: () => editor.chain().focus().deleteColumn().run(), class: 'text-red-600' },
      { text: '删除表格', cmd: () => editor.chain().focus().deleteTable().run(), class: 'text-red-600' },
    ];

    buttons.forEach(({ text, cmd, class: className = '' }) => {
      const button = document.createElement('button');
      button.className = `px-2 py-1 text-xs bg-white border rounded hover:bg-gray-50 ${className}`;
      button.textContent = text;
      button.onclick = cmd;
      toolbar.appendChild(button);
    });

    document.body.appendChild(toolbar);

    const updateToolbarPosition = () => {
      const { state } = editor.view;
      const { selection } = state;
      const { $anchor } = selection;
      
      let isInTable = false;
      let depth = $anchor.depth;
      
      while (depth > 0) {
        const node = $anchor.node(depth);
        if (node.type.name === 'table') {
          isInTable = true;
          break;
        }
        depth--;
      }

      if (isInTable) {
        const coords = editor.view.coordsAtPos($anchor.pos);
        toolbar.style.display = 'flex';
        toolbar.style.top = `${coords.top - toolbar.offsetHeight - 8}px`;
        toolbar.style.left = `${coords.left}px`;
      } else {
        toolbar.style.display = 'none';
      }
    };

    editor.on('selectionUpdate', updateToolbarPosition);
    editor.on('focus', updateToolbarPosition);
    editor.on('blur', () => {
      setTimeout(() => {
        if (!editor.isActive('table')) {
          toolbar.style.display = 'none';
        }
      }, 200);
    });

    this.storage.toolbar = toolbar;
  },

  onDestroy() {
    if (this.storage.toolbar) {
      this.storage.toolbar.remove();
    }
  },

  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey('tableToolbar'),
      })
    ]
  }
})